from django.http import JsonResponse
from django.views import View
from datetime import date, timedelta

from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from goods.models import GoodsVisitCount
from meiduo_admin.home.serializers import GoodsVisitCountSerializer
from orders.models import OrderInfo
from users.models import User


# 获取总人数
class UserTotalCountView(View):
    def get(self, request):
        count = User.objects.filter(is_staff=False, is_superuser=False).count()
        return JsonResponse({'count': count}, status=200)


# 获取下单人数
class UserDayOrdersCountView(View):
    def get(self, request):
        # count = OrderInfo.objects.filter(create_time=date.today()).count()
        count = User.objects.filter(orders__create_time__gte=date.today()).count()
        return JsonResponse({'count': count}, status=200)


# 获取日活人数
class UserDayActiveCountView(View):
    def get(self, request):
        count = User.objects.filter(last_login__gte=date.today(), is_staff=False).count()
        return JsonResponse({'count': count}, status=200)


# 获取日增人数
class UserDayIncrementCountView(View):
    def get(self, request):
        count = User.objects.filter(date_joined__gte=date.today(), is_staff=False).count()
        return JsonResponse({'count': count}, status=200)


# 获取月新增用户
class UserMonthIncrementCountView(APIView):
    def get(self, request):
        incre_user_list = []
        last_day = date.today() - timedelta(days=29)
        for day in range(30):
            next_day = last_day + timedelta(days=1)

            count = User.objects.filter(date_joined__gte=last_day, date_joined__lt=next_day, is_staff=False).count()

            incre_user_list.append({'count': count, 'date': last_day})
            last_day = next_day

        return Response(incre_user_list, status=200)


# 获取商品访问量
class GoodsDayVisitCountView(ListAPIView):
    queryset = GoodsVisitCount.objects.filter(date=date.today())
    serializer_class = GoodsVisitCountSerializer
